# -*- coding: utf-8 -*-
# @Time    : 2023/5/5 10:29
# @Author  : Jonny
# @File    : LuckGitlabApi.py

import gitlab
import requests

class LuckGitlabApi(object):

    def __init__(self, gitlab_private_token, gitlab_server_url):
        self.gitlab_private_token = gitlab_private_token
        self.gitlab_server_url = gitlab_server_url
        self.gl = gitlab.Gitlab(
            gitlab_server_url,
            private_token=gitlab_private_token,
            timeout=300,
            api_version='4'
        )
        print('初始化GitLab连接成功')

    # 修改项目显示权限
    def change_project_visibility(self, project_id, visibility):
        project = self.read_one_project(project_id)
        project.visibility = visibility
        project.save()

        # 获取所有的项目

    def read_all_projects(self):
        self.projects = self.gl.projects.list(all=True)
        print('self.projects', self.projects)
        return self.projects

    # 获取指定的项目
    def read_one_project(self, project_id):
        self.project = self.gl.projects.get(project_id)
        print('self.project', self.project)
        return self.project

    # 获取所有的合并请求
    def read_all_merge_requests(self):
        self.mergerequests = self.project.mergerequests.list(scope="all")
        print('self.mergerequests', self.mergerequests)
        return self.mergerequests

    # 获取指定的合并请求
    def read_one_merge_request(self, merge_request_id):
        self.mergerequest = self.project.mergerequests.get(merge_request_id)
        print('self.mergerequest', self.mergerequest)
        return self.mergerequest

    # 获取合并请求不同
    def read_all_merge_request_changes(self):
        self.changes = self.mergerequest.changes()
        print('self.changes', self.changes)
        return self.changes

    # 获取所有分支的提交
    def read_branch_all_commits(self, branch_name):
        self.commits = self.project.commits.list(ref_name=branch_name)
        print('self.commits', self.commits)
        return self.commits

    # 获取所有分支的提交
    def read_branch_last_commit(self, branch_name):
        commits = self.project.commits.list(ref_name=branch_name)
        self.commit = None
        for c in commits:
            if self.commit is not None:
                break
            # 获取指定commit信息
            self.commit = self.project.commits.get(c.short_id)
        print('self.commit ', self.commit)
        return self.commit

    # 获取指定的提交
    def read_commit_by_id(self, commit_id):
        # 获取指定commit信息
        self.commit = self.project.commits.get(commit_id)
        print('self.commit ', self.commit)
        return self.commit

    # 获取指定项目的用户贡献
    def read_contributors_by_project_id(self, project_id):
        headers = {'PRIVATE-TOKEN': self.gitlab_private_token}  # GitLab 需要这个头部来验证你的请求
        url = f"{self.gitlab_server_url}/api/v4/projects/{project_id}/repository/contributors"
        # 发送 GET 请求
        response = requests.get(url, headers=headers)

        # 检查请求是否成功
        if response.status_code == 200:
            # 打印返回的 JSON 数据
            data = response.json()
            return data

    # 获取指定用户ID的用户信息
    def read_user_by_id(self, user_id):
        headers = {'PRIVATE-TOKEN': self.gitlab_private_token}  # GitLab 需要这个头部来验证你的请求
        url = f"{self.gitlab_server_url}/api/v4/users/{user_id}"
        # 发送 GET 请求
        response = requests.get(url, headers=headers)

        # 检查请求是否成功
        if response.status_code == 200:
            # 打印返回的 JSON 数据
            data = response.json()
            return data

    # 获取指定用户账号的用户信息
    def read_user_by_username(self, username):
        headers = {'PRIVATE-TOKEN': self.gitlab_private_token}  # GitLab 需要这个头部来验证你的请求
        url = f"{self.gitlab_server_url}/api/v4/users"
        params = {
            'username': username
        }
        # 发送 GET 请求
        response = requests.get(url, headers=headers, params=params)

        # 检查请求是否成功
        if response.status_code == 200:
            # 打印返回的 JSON 数据
            data = response.json()
            return data

    # 获取全部用户信息
    def read_all_user(self):
        headers = {'PRIVATE-TOKEN': self.gitlab_private_token}
        url = f"{self.gitlab_server_url}/api/v4/users"
        users = []
        page = 1
        while True:
            # 请求参数
            params = {
                'per_page': 100,  # 每页返回的用户数量（最多100）
                'page': page
            }
            response = requests.get(url, headers=headers, params=params)
            if response.status_code == 200:
                data = response.json()
                print(f"第{page}页有{len(data)}个用户")
                if not data:  # 如果没有更多用户，结束循环
                    break
                users.extend(data)
                page += 1
            else:
                print(f'请求失败，状态码: {response.status_code}')
                break
        print(f"共{len(users)}个用户")

        return users

    def read_user_detail(self, user_id):
        headers = {'PRIVATE-TOKEN': self.gitlab_private_token}  # GitLab 需要这个头部来验证你的请求
        url = f"{self.gitlab_server_url}/api/v4/users/{user_id}"
        response = requests.get(url, headers=headers)

        if response.status_code == 200:
            return response.json()
        else:
            print(f'获取用户详情失败，状态码: {response.status_code}')
            return None

    # 读取全部用户详情信息
    def read_all_user_details(self):
        users = self.read_all_user()
        detailed_users = []

        for user in users:
            user_id = user.get('id')
            if user_id:
                user_detail = self.read_user_detail(user_id)
                if user_detail:
                    detailed_users.append(user_detail)

        return detailed_users
